<template>
    <!--配合specTree.vue使用-->
    <view class="spec-tree-item">
        <view v-if="noLast">
            <!-- 不是最后一组规格 -->
            <view class="sku-item">
                <view class="sku-item-title"
                    ><text>{{ getTreeData[0].AttributeName }}：</text></view
                >
                <view class="sku-item-select">
                    <view
                        v-for="(item, index) in getTreeData"
                        :key="index"
                        class="btn btn-gray-fill"
                        :class="activeIndex === index ? 'btn-success-fill' : ''"
                        @click="_clickEvent(item, index)">
                        {{ item.ValueStr }}
                    </view>
                </view>
                <view
                    v-if="getTreeData[0].ProductAttrList && getTreeData[0].ProductAttrList.length > 0"
                    class="spec-sub-tree">
                    <!--SpecTreeItem组件中调用SpecTreeItem组件-->
                    <!-- 根据上级规格的数量创建多个item，根据上级规格选中的项来显示对应的下级规格栏-->
                    <view v-for="(item, index) in getTreeData" v-show="activeIndex === index" :key="index">
                        <SpecTreeItem
                            :data="data"
                            :tree-data="item.ProductAttrList"
                            :active-id="activeId"
                            :min-num="minNum"
                            :limit-buy="limitBuy"
                            @treeClickEvent="treeClickEvent"
                            @setCarListFunc="setCarListFunc"
                            :tempType="tempType"
                            :addNum="addNum" />
                    </view>
                </view>
            </view>
        </view>
        <view v-else>
            <!-- 是最后一组规格 -->
            <!-- 根据上级规格的数量创建多个item，根据上级规格选中的项来显示对应的下级规格栏-->
            <view v-for="(item, index) in getTreeData" :key="index" class="num-item" v-if="item.SkuModel">
                <view v-if="item.ValueStr && getTreeData[0] && getTreeData[0].AttributeName" class="num-value">
                    {{ item.ValueStr }}
                    <view class="num-price">￥{{ getShowPrice(item.SkuModel.ProductUnitPrice.Price) }}</view>
                </view>
                <view v-else class="mask-box"></view>
                <!-- <text class="num-value" >{{ item.SkuModel.ProductUnitPrice.Price }}</text>
					<text class="num-value">{{ item.SkuModel.Stock }}</text> -->
                <view v-if="tempType == 0">
                    <view class="input-number-box">
                        <text
                            class="btn-minus"
                            :class="item.Amount <= 0 ? 'color-shadow' : ''"
                            @click="
                                changeAmount(
                                    item,
                                    item.Amount,
                                    item.Stock,
                                    -1,
                                    minNum,
                                    item.Ratio,
                                    limitBuy,
                                    item.AddNum,
                                )
                            "
                            >-</text
                        >
                        <view class="btn-input-box">
                            <input
                                v-model="item.Amount"
                                type="digit"
                                class="btn-input"
                                @click="inputclick(item)"
                                @blur="
                                    changeAmount(
                                        item,
                                        item.Amount,
                                        item.Stock,
                                        0,
                                        minNum,
                                        item.Ratio,
                                        limitBuy,
                                        item.AddNum,
                                    )
                                " />
                        </view>
                        <text
                            class="btn-plus"
                            :class="
                                item.Amount * item.Ratio >= item.Stock ||
                                (item.Amount * item.Ratio >= limitBuy && limitBuy > 0)
                                    ? 'color-shadow'
                                    : ''
                            "
                            @click="
                                changeAmount(
                                    item,
                                    item.Amount,
                                    item.Stock,
                                    1,
                                    minNum,
                                    item.Ratio,
                                    limitBuy,
                                    item.AddNum,
                                )
                            "
                            >+</text
                        >
                    </view>
                    <text class="num-price">库存：{{ item.SkuModel.Stock }}</text>
                </view>
                <view v-else>
                    <view class="input-number-box">
                        <text
                            class="btn-minus"
                            :class="item.Amount <= 0 ? 'color-shadow' : ''"
                            @click="
                                changeAmount(
                                    item,
                                    item.Amount,
                                    item.Stock,
                                    -1,
                                    minNum,
                                    item.Ratio,
                                    limitBuy,
                                    item.AddNum,
                                )
                            "
                            >-</text
                        >
                        <view class="btn-input-box">
                            <input
                                v-model="item.Amount"
                                type="digit"
                                class="btn-input"
                                @blur="
                                    changeAmount(
                                        item,
                                        item.Amount,
                                        item.Stock,
                                        0,
                                        minNum,
                                        item.Ratio,
                                        limitBuy,
                                        item.AddNum,
                                    )
                                " />
                        </view>
                        <text
                            class="btn-plus"
                            @click="
                                changeAmount(
                                    item,
                                    item.Amount,
                                    item.Stock,
                                    1,
                                    minNum,
                                    item.Ratio,
                                    limitBuy,
                                    item.AddNum,
                                )
                            "
                            >+</text
                        >
                    </view>
                </view>
                <num-popup v-if="numPopShow" :amount="item.Amount" @close="numPopupClose" @up="numPopupUp"></num-popup>
            </view>
        </view>
    </view>
</template>

<script>
import { mapMutations, mapGetters } from "vuex"
import SpecTreeItem from "@/components/product/spec-tree-item.vue"

import utilsOld from "@/utils/utilsOld.js"
import { getAmountInTempCart, getAmountInTempCartAct } from "@/utils/tempCartUtil.js"
import numPopup from "@/components/order/num-popup.vue"
import storage from "@/uni-sub-base/utils/storage.js"
import { eventBus } from "@/utils/eventBus.js"
export default {
    name: "SpecTreeItem",
    components: {
        SpecTreeItem,
        numPopup,
    },
    props: {
        data: {
            // 数据
            type: Object,
            required: true,
        },
        treeData: {
            type: Array,
            default() {
                return []
            },
        },
        activeId: {
            type: Number,
            default: -1,
        },
        minNum: {
            type: Number,
            default: 0,
        },
        limitBuy: {
            type: Number,
            default: 0,
        },
        isSingle: {
            type: Boolean,
            default: false,
        },
        tempType: {
            type: Number,
            default: 0,
        },
        addNum: {
            type: Number,
            default: 1,
        },
    },
    watch: {
        //监听临时购物车数据
        getTempCartData(data) {},
    },
    computed: {
        ...mapGetters(["getTempCartData"]),
    },
    data() {
        return {
            numPopShow: false,
            activeIndex: -1,
            numValue: 0,
            noLast: false,
            getTreeData: [],
            objItem: 0,
            cartDatas: [],
        }
    },
    mounted() {
        this.getTreeData = this.treeData
        this.noLast =
            this.getTreeData &&
            this.getTreeData.length > 0 &&
            this.getTreeData[0].ProductAttrList &&
            this.getTreeData[0].ProductAttrList.length > 0
        if (!this.noLast) {
            this.getTreeData.forEach((e) => {
                this.getCurrentNum(e)
            })
        }
        this.$forceUpdate()
        //监听广播 获取购物车数据
        eventBus.$on("SET_CART_FOR_SUB", (msg) => {
            if (msg) {
                this.cartDatas = msg
                if (!this.noLast) {
                    this.getTreeData.forEach((e) => {
                        this.getCurrentNum(e)
                    })
                }
                this.$forceUpdate()
            }
        })
        //广播获取获购物车数据
        eventBus.$emit("GET_CART_DATA_FOR_SUB", "")
    },
    destroyed() {
        //取消监听
        eventBus.$off("SET_CART_FOR_SUB")
    },
    methods: {
        getShowPrice(price) {
            let productDisplay = storage.getCache("productDisplay")
            if (productDisplay) {
                return price.toFixed(productDisplay.PriceDecimalPlaces ? productDisplay.PriceDecimalPlaces : 2)
            }
            return price
        },
        inputclick(item) {
            this.objItem = item.Amount
            // this.$nextTick(()=>{
            // 	this.numPopShow = true
            // })
        },
        getCurrentNum(item) {
            if (this.tempType == 0) {
                this.cartDatas.forEach((e) => {
                    if (e.ProductId == item.ProductId) {
                        e.SubItems.forEach((sub) => {
                            if (sub.SkuId == item.SkuId && item.UnitId == sub.UnitId) {
                                item.Amount = sub.Amount
                            }
                        })
                    }
                })
            } else if (this.tempType == 1) {
                let amount = getAmountInTempCart(item)
                item.Amount = amount
            } else if (this.tempType == 3) {
                let amount = getAmountInTempCartAct(item)
                item.Amount = amount
            }
            if (item.Amount > 0) {
                this.setCarListFunc(item)
            }
        },
        //获取购买数量
        getAmount(num) {
            return num
        },
        // 节点点击事件
        _clickEvent(item, index) {
            this.activeIndex = index

            // 如果有传递事件函数，则调用事件函数并传递当前节点数据及组件
            this.treeClickEvent(item, index)
        },
        changeAmount(item, num, stock, type, minNum, UnitRatio, LimitBuy, addNum) {
            addNum = this.addNum
            const _oldAmount = item.Amount
            num = Number(num)
            addNum = UnitRatio && UnitRatio == 1 ? addNum : 1
            addNum = addNum == 0 ? 1 : addNum
            if (this.tempType == 1 || this.getAppSet().NoCheckStock) {
                if (type != 0) {
                    item.Amount = num + Number(type) * addNum
                    if (type == -1 && item.Amount * UnitRatio < minNum) {
                        item.Amount = 0
                    } else if (item.Amount * UnitRatio < minNum) {
                        minNum = parseInt(minNum / UnitRatio) + (minNum % UnitRatio > 0 ? 1 : 0)
                        let addN = minNum % addNum
                        let newNum = utilsOld.getMaxNum(minNum, addNum, addN)
                        item.Amount = newNum
                    }
                } else {
                    if (num > 0) {
                        let addN = num % addNum
                        let newNum = utilsOld.getMaxNum(num, addNum, addN)
                        item.Amount = newNum
                        if (item.Amount * UnitRatio < minNum) {
                            minNum = parseInt(minNum / UnitRatio) + (minNum % UnitRatio > 0 ? 1 : 0)
                            let addN = minNum % addNum
                            let newNum = utilsOld.getMaxNum(minNum, addNum, addN)
                            item.Amount = newNum
                        }
                    } else {
                        item.Amount = 0
                    }
                }

                if (item.Amount < 0) {
                    item.Amount = 0
                }
            } else {
                utilsOld.changeAmountNew(item, num, stock, type, minNum, UnitRatio, LimitBuy, addNum)
            }
            if (_oldAmount !== item.Amount || type === 0) {
                const _obj = {}
                _obj.ProductId = item.ProductId
                _obj.Amount = item.Amount
                _obj.SkuId = item.SkuId
                _obj.UnitId = item.UnitId
                _obj.UnitName = item.UnitName
                _obj.ValueId = item.ValueId
                _obj.Ratio = item.Ratio
                _obj.CartProductName = this.data.ProductName
                _obj.CartProductPrice = item.V_FactPrice
                _obj.CartProductImage = item.SkuModel.SkuImg
                _obj.CartProductAttribute = item.V_AttributeNameValue

                // 同步多规格要加入购物车的数据
                this.setCarListFunc(_obj)
                this.$forceUpdate()
            }
        },
        setCarListFunc(obj) {
            this.$emit("setCarListFunc", obj)
            this.$forceUpdate()
        },
        treeClickEvent(item, index) {
            this.$emit("treeClickEvent", item, index)
        },
        numPopupClose(e) {
            this.numPopShow = false
        },
        numPopupUp(e) {
            // this.batchItem.Amount = e

            this.numPopShow = false
        },
    },
}
</script>
<style lang="scss" scoped>
.spec-tree-item {
    .sku-item {
        display: flex;
        flex-direction: column;
        margin-bottom: 20rpx;

        .sku-item-title {
        }

        .sku-item-select {
            display: flex;
            flex-direction: row;
            flex-wrap: wrap;
            margin: 20rpx 0 0;

            .btn {
                min-width: 100rpx;
                border-radius: $border-radius-10;
                margin-right: 20rpx;
                margin-bottom: 20rpx;
            }
        }
    }

    .num-title {
        display: flex;
        flex-direction: row;
        margin-bottom: 20rpx;
        border-top: solid 1rpx $app-color-input-bg;
        padding-top: $app-page-padding;

        .title-label {
            display: flex;
            flex: 1;
        }

        .buy-num {
            display: flex;
            width: 234rpx;
            justify-content: center;
        }
    }
}

.num-item {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    margin-bottom: 24rpx;
    align-items: center;

    text {
        display: flex;
        flex: 1;
    }

    .num-value {
        font-size: 28rpx;
        color: $color-gray-1;
    }

    .num-price {
        font-size: 20rpx;
        color: $color-gray-3;
    }
}
.btn-input {
    font-size: 30rpx;
}
.mask-box {
    flex: 1;
}
</style>
